/*
 * Copyright (c) 2011, Marc-Andre Ferland - madrang@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the The Warrent Team nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *     * This software is free for non-commercial use. You may not use this
 *       software, in whole or in part, in support of any commercial product
 *       without the express consent of the author.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE WARRENT TEAM BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;

namespace OsHelper.UsbNet
{
	public class LibUsbDevice : UsbDevice
	{
		private LibUsb.Profile pro_Profile;
		private LibUsb.Device dev_Device;
		
		private List<int> ls_KernelReleaseList;
		
		private LibUsbDevice () : base()
		{
			this.ls_KernelReleaseList = new List<int>();
		}
		
		private LibUsbDevice (LibUsb.Profile MyProfile) : this()
		{
			this.pro_Profile = MyProfile;
		}
		
		public LibUsbDevice (short VendorID, short ProductID) : this()
		{
			this.dev_Device = new LibUsb.Device(LibUsbSession, VendorID, ProductID);
			this.pro_Profile = new LibUsb.Profile(this.dev_Device);
		}
		
		#region Method
		
		public override void Open()
		{
			if(!this.IsOpen) {
				this.dev_Device = new UsbNet.LibUsb.Device(this.pro_Profile);
			}
		}
		
		public override void Close()
		{
			base.Close();
			
			if(this.IsOpen) {
				this.dev_Device.Dispose();
			}
		}
		
		public override void Dispose()
		{
			base.Dispose();
			
			this.pro_Profile.Dispose();
		}
		
		public override void ResetDevice ()
		{
			this.CheckOpen("Can't reset a closed device.");
			
			this.dev_Device.Reset();
		}
		
		#endregion
		
		#region Interface
		
		public override void SetAlternateInterface (int InterfaceID, byte AltInterfaceID)
		{
			this.dev_Device.SetInterfaceAltSetting(InterfaceID, AltInterfaceID);
		}
		
		public override void ClaimInterface (int InterfaceID)
		{
			this.CheckOpen("Can't claim interface of a closed device.");
			
			if(this.dev_Device.KernelDriverActive(InterfaceID)) {
				this.ls_KernelReleaseList.Add(InterfaceID);
				this.dev_Device.DetachKernelDriver(InterfaceID);
			}
			this.dev_Device.ClaimInterface(InterfaceID);
			
			base.ClaimInterface(InterfaceID);
		}
		
		public override void ReleaseInterface (int InterfaceID)
		{
			this.CheckOpen("Can't release interface of a closed device.");
			
			base.ReleaseInterface(InterfaceID);
			
			this.dev_Device.ReleaseInterface(InterfaceID);
			
			if(this.ls_KernelReleaseList.Contains(InterfaceID)) {
				this.ls_KernelReleaseList.Remove(InterfaceID);
				this.dev_Device.AttachKernelDriver(InterfaceID);
			}
		}
		
		#endregion
		
		#region Transfer
		
		public override int Transfer(UsbNet.Descriptors.EndpointDescriptor Endpoint, byte[] Data, int Length, int Timeout)
		{
			this.CheckOpen("Can't receive data while device is not open.");
			
			if(Endpoint.Attributes.Transfer == OsHelper.UsbNet.Descriptors.TransferType.Bulk)
				return this.dev_Device.BulkTransfer(Endpoint.Address, Data, Length, Timeout);
			else if(Endpoint.Attributes.Transfer == OsHelper.UsbNet.Descriptors.TransferType.Interrupt)
				return this.dev_Device.InterruptTransfer(Endpoint.Address, Data, Length, Timeout);
			else throw new NotSupportedException();
		}
		
		public override int ControlTransfer (RequestAttributes MyAttributes, byte RequestType, short Value, short Index, byte[] Data, short Length, int Timeout)
		{
			this.CheckOpen("Can't receive data while device is not open.");
			
			return this.dev_Device.ControlTransfer(MyAttributes, RequestType,
			                                       Value, Index,
			                                       Data, Length, Timeout);
		}
		
		#endregion
		
		#region Properties
		
		public override byte BusNumber {
			get {
				return this.pro_Profile.BusNumber;
			}
		}
		
		public override byte DeviceAddress {
			get {
				return this.pro_Profile.DeviceAddress;
			}
		}
		
		public override bool IsOpen {
			get {
				return (this.dev_Device != null && !this.dev_Device.IsInvalid);
			}
		}
		
		public override byte Configuration {
			get {
				this.CheckOpen("Can't receive data while device is not open.");
				return (byte)this.dev_Device.Configuration;
			}
			set {
				this.CheckOpen("Can't send data while device is not open.");
				this.dev_Device.Configuration = value;
			}
		}
		
		public override Descriptors.DeviceDescriptor DeviceDescriptor {
			get {
				return this.pro_Profile.DeviceDescriptor;
			}
		}
		
		#endregion
		
		#region Static
		
		private static LibUsb.Session LibUsbSession = new LibUsb.Session();
		
		public static List<UsbDevice> LibUsbDevices {
			get {
				List<UsbDevice> ResultList = new List<UsbDevice>();
				
				foreach (LibUsb.Profile ProfileItem in LibUsb.Profile.GetProfileList(LibUsbSession)) {
					ResultList.Add(new LibUsbDevice(ProfileItem));
				}
				
				return ResultList;
			}
		}
		
		#endregion
	}
}
